import { useState, useEffect, useCallback, useRef } from 'react';
import { User, Product } from '../types';
import { apiService } from '../services/api';
import { debounce } from '../utils';

// 通用加载状态Hook
export const useLoading = (initialState: boolean = false) => {
  const [isLoading, setIsLoading] = useState(initialState);
  const [error, setError] = useState<string | null>(null);

  const startLoading = useCallback(() => {
    setIsLoading(true);
    setError(null);
  }, []);

  const stopLoading = useCallback(() => {
    setIsLoading(false);
  }, []);

  const setLoadingError = useCallback((errorMessage: string) => {
    setIsLoading(false);
    setError(errorMessage);
  }, []);

  const resetError = useCallback(() => {
    setError(null);
  }, []);

  return {
    isLoading,
    error,
    startLoading,
    stopLoading,
    setLoadingError,
    resetError,
  };
};

// 异步数据获取Hook
export const useAsyncData = <T>(
  asyncFunction: () => Promise<T>,
  dependencies: any[] = []
) => {
  const [data, setData] = useState<T | null>(null);
  const { isLoading, error, startLoading, stopLoading, setLoadingError } = useLoading();

  const fetchData = useCallback(async () => {
    startLoading();
    try {
      const result = await asyncFunction();
      setData(result);
      stopLoading();
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'An error occurred');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [startLoading, stopLoading, setLoadingError, ...dependencies]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return {
    data,
    isLoading,
    error,
    refetch: fetchData,
  };
};

// 用户数据Hook
export const useUsers = () => {
  const [users, setUsers] = useState<User[]>([]);
  const { isLoading, error, startLoading, stopLoading, setLoadingError } = useLoading();

  const fetchUsers = useCallback(async () => {
    startLoading();
    try {
      const response = await apiService.getUsers();
      setUsers(response.data);
      stopLoading();
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to fetch users');
    }
  }, [startLoading, stopLoading, setLoadingError]);

  const createUser = useCallback(async (userData: any) => {
    startLoading();
    try {
      const response = await apiService.createUser(userData);
      setUsers(prev => [...prev, response.data]);
      stopLoading();
      return response.data;
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to create user');
      throw err;
    }
  }, [startLoading, stopLoading, setLoadingError]);

  const updateUser = useCallback(async (id: number, userData: Partial<User>) => {
    startLoading();
    try {
      const response = await apiService.updateUser(id, userData);
      setUsers(prev => prev.map(user => user.id === id ? response.data : user));
      stopLoading();
      return response.data;
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to update user');
      throw err;
    }
  }, [startLoading, stopLoading, setLoadingError]);

  const deleteUser = useCallback(async (id: number) => {
    startLoading();
    try {
      await apiService.deleteUser(id);
      setUsers(prev => prev.filter(user => user.id !== id));
      stopLoading();
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to delete user');
      throw err;
    }
  }, [startLoading, stopLoading, setLoadingError]);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  return {
    users,
    isLoading,
    error,
    refetch: fetchUsers,
    createUser,
    updateUser,
    deleteUser,
  };
};

// 产品数据Hook
export const useProducts = (page: number = 1, limit: number = 10) => {
  const [products, setProducts] = useState<Product[]>([]);
  const [totalPages, setTotalPages] = useState(0);
  const [total, setTotal] = useState(0);
  const { isLoading, error, startLoading, stopLoading, setLoadingError } = useLoading();

  const fetchProducts = useCallback(async () => {
    startLoading();
    try {
      const response = await apiService.getProducts(page, limit);
      setProducts(response.data.data);
      setTotalPages(response.data.totalPages);
      setTotal(response.data.total);
      stopLoading();
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to fetch products');
    }
  }, [page, limit, startLoading, stopLoading, setLoadingError]);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  return {
    products,
    totalPages,
    total,
    isLoading,
    error,
    refetch: fetchProducts,
  };
};

// 单个产品Hook
export const useProduct = (id: number) => {
  const [data, setData] = useState<Product | null>(null);
  const { isLoading, error, startLoading, stopLoading, setLoadingError } = useLoading();

  const fetchProduct = useCallback(async () => {
    if (!id || id <= 0) {
      setData(null);
      return;
    }

    startLoading();
    try {
      const response = await apiService.getProductById(id);
      setData(response.data);
      stopLoading();
    } catch (err) {
      setLoadingError(err instanceof Error ? err.message : 'Failed to fetch product');
    }
  }, [id, startLoading, stopLoading, setLoadingError]);

  useEffect(() => {
    fetchProduct();
  }, [fetchProduct]);

  return {
    data,
    isLoading,
    error,
    refetch: fetchProduct,
  };
};

// 本地存储Hook
export const useLocalStorage = <T>(key: string, initialValue: T) => {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

  const setValue = useCallback((value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error);
    }
  }, [key, storedValue]);

  return [storedValue, setValue] as const;
};

// 防抖Hook
export const useDebounce = <T>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};

// 搜索Hook
export const useSearch = <T>(
  items: T[],
  searchFields: (keyof T)[],
  initialQuery: string = ''
) => {
  const [query, setQuery] = useState(initialQuery);
  const debouncedQuery = useDebounce(query, 300);

  const filteredItems = useCallback(() => {
    if (!debouncedQuery.trim()) return items;

    return items.filter(item =>
      searchFields.some(field => {
        const value = item[field];
        return String(value).toLowerCase().includes(debouncedQuery.toLowerCase());
      })
    );
  }, [items, searchFields, debouncedQuery]);

  return {
    query,
    setQuery,
    filteredItems: filteredItems(),
    isSearching: query !== debouncedQuery,
  };
};

// 分页Hook
export const usePagination = (totalItems: number, itemsPerPage: number = 10) => {
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.ceil(totalItems / itemsPerPage);

  const goToPage = useCallback((page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)));
  }, [totalPages]);

  const goToNextPage = useCallback(() => {
    goToPage(currentPage + 1);
  }, [currentPage, goToPage]);

  const goToPreviousPage = useCallback(() => {
    goToPage(currentPage - 1);
  }, [currentPage, goToPage]);

  const goToFirstPage = useCallback(() => {
    goToPage(1);
  }, [goToPage]);

  const goToLastPage = useCallback(() => {
    goToPage(totalPages);
  }, [goToPage, totalPages]);

  return {
    currentPage,
    totalPages,
    goToPage,
    goToNextPage,
    goToPreviousPage,
    goToFirstPage,
    goToLastPage,
    hasNextPage: currentPage < totalPages,
    hasPreviousPage: currentPage > 1,
  };
};

// 窗口大小Hook
export const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = debounce(() => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }, 100);

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;
};

// 点击外部Hook
export const useClickOutside = (callback: () => void) => {
  const ref = useRef<HTMLElement>(null);

  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [callback]);

  return ref;
};